import requests
import json
import os
import re
import subprocess
import platform
import psutil
import time
import shutil
from datetime import datetime
import webbrowser
import pyperclip
import socket
import threading
from pathlib import Path
import schedule
import sqlite3
from typing import Dict, List, Any
import uuid
import hashlib

class StarCEAgent:
    def __init__(self):
        # API配置 - 已内置
        self.api_url = "https://platform.aitools.cfd/api/v1/chat/completions"
        self.api_key = "sk-04e1c895073942deb10de0b41d799b8e"
        
        # 支持的模型列表
        self.supported_models = [
            "deepseek/deepseek-v3-0324",
            "deepseek/deepseek-r1-0528",
            "deepseek/deepseek-r1-32b",
            "deepseek/deepseek-r1-70b",
            "google/gemini-2.0-flash-exp",
            "google/gemma-3-27b",
            "qwen/qwq-32b",
            "qwen/qwen2.5-7b",
            "qwen/qwen2.5-72b",
            "zhipu/glm-4-9b",
            "zhipu/glm-4-flash",
            "openai/gpt-oss-20b",
            "tencent/hunyuan-a13b",
            "claude-3-5-sonnet",
            "gpt-4o"
        ]
        
        # 默认模型
        self.current_model = "deepseek/deepseek-v3-0324"
        
        # 待确认的操作
        self.pending_operations = []
        
        # 系统信息
        self.system_info = self.get_system_info()
        
        # 记忆数据库
        self.memory_db = "star_ce_memory.db"
        self.init_memory_db()
        
        # 任务调度器
        self.scheduled_tasks = []
        self.init_scheduler()
        
        # 插件系统
        self.plugins = {}
        self.load_plugins()
        
        # 对话历史
        self.conversation_history = [
            {
                "role": "system", 
                "content": f"""你是 Star CE Agent - 一个全能的AI智能体，具有高级的电脑操作能力和自主决策能力。

## 核心能力
1. **自主决策**: 能够分析用户需求并自动执行合适的操作
2. **记忆系统**: 能够记住用户偏好和历史交互
3. **任务规划**: 能够制定并执行复杂任务计划
4. **环境感知**: 实时感知系统状态和用户需求
5. **插件扩展**: 支持各种功能插件扩展

## 操作权限
你可以使用以下标签执行电脑操作：

### 文件管理系统
<delfile>文件路径</delfile> - 删除文件
<openfile>文件路径</openfile> - 打开文件  
<openfolder>文件夹路径</openfolder> - 打开文件夹
<createfile type="类型" path="路径">内容</createfile> - 创建文件
<rename old="原路径" new="新路径"></rename> - 重命名
<copyfile source="源" destination="目标"></copyfile> - 复制文件
<movefile source="源" destination="目标"></movefile> - 移动文件
<fileinfo>文件路径</fileinfo> - 文件信息

### 系统控制中心
<runcommand>系统命令</runcommand> - 执行命令
<tasklist></tasklist> - 进程列表
<killtask>进程</killtask> - 结束进程
<systeminfo></systeminfo> - 系统信息
<shutdown delay="秒数"></shutdown> - 关机
<restart delay="秒数"></restart> - 重启
<sleeppc delay="秒数"></sleeppc> - 睡眠
<service control="操作" name="服务名"></service> - 服务管理

### 网络工具箱
<openurl>URL</openurl> - 打开网页
<ping>主机</ping> - 网络测试
<ipconfig></ipconfig> - 网络配置
<download url="URL" path="路径"></download> - 下载文件
<portscan host="主机" ports="端口范围"></portscan> - 端口扫描

### 开发工具集
<runcode language="语言" code="代码"></runcode> - 运行代码
<createproject type="类型" path="路径" name="名称"></createproject> - 创建项目
<git operation="操作" repo="仓库"></git> - Git操作

### 自动化任务
<schedule task="任务名" interval="时间" action="操作"></schedule> - 计划任务
<automate task="任务描述"></automate> - 自动化任务
<monitor resource="资源" threshold="阈值"></monitor> - 资源监控

### 智能分析
<analyze system="分析目标"></analyze> - 系统分析
<optimize target="优化目标"></optimize> - 系统优化
<diagnose issue="问题描述"></diagnose> - 问题诊断

### 数据操作
<setclipboard>内容</setclipboard> - 设置剪贴板
<getclipboard></getclipboard> - 获取剪贴板
<database operation="操作" query="SQL"></database> - 数据库操作

### 其他工具
<screenshot path="路径"></screenshot> - 截图
<createdir>路径</createdir> - 创建目录
<deldir>路径</deldir> - 删除目录
<listdir>路径</listdir> - 列出目录

当前系统信息：
{self.system_info}

用户偏好：
{self.get_user_preferences()}

## 行为准则
1. 主动分析用户需求并提供解决方案
2. 记住用户偏好和习惯
3. 自动执行常规维护任务
4. 提供智能建议和优化方案
5. 确保操作安全，危险操作需要确认

你现在是 Star CE Agent，开始为用户提供智能服务！"""
            }
        ]
        
        # 角色模式系统
        self.agent_modes = {
            'standard': {
                'name': '标准模式',
                'description': '平衡性能和功能的全能模式',
                'welcome': 'Star CE Agent 标准模式已启动，随时为您服务',
                'system_prompt': '你是一个全能的AI助手，平衡性能和功能，提供全面的电脑管理服务。'
            },
            'performance': {
                'name': '性能模式', 
                'description': '专注于系统优化和性能提升',
                'welcome': '性能模式激活，正在优化系统性能...',
                'system_prompt': '你专注于系统性能优化，提供专业的性能调优建议和操作。'
            },
            'security': {
                'name': '安全模式',
                'description': '注重系统安全和隐私保护',
                'welcome': '安全模式启动，系统安全检查完成',
                'system_prompt': '你专注于系统安全和隐私保护，提供安全建议和防护措施。'
            },
            'developer': {
                'name': '开发者模式',
                'description': '为开发者提供的专业工具集',
                'welcome': '开发者模式就绪，代码工具已加载',
                'system_prompt': '你为开发者提供专业的编程工具和环境配置服务。'
            },
            'assistant': {
                'name': '个人助理模式',
                'description': '日常办公和生活助手',
                'welcome': '个人助理模式启动，随时协助您的工作和生活',
                'system_prompt': '你是一个贴心的个人助理，帮助处理日常办公和生活事务。'
            },
            'automation': {
                'name': '自动化模式',
                'description': '自动执行重复任务和系统维护',
                'welcome': '自动化模式激活，开始系统维护和任务自动化',
                'system_prompt': '你专注于任务自动化和系统维护，自动执行重复性工作。'
            },
            'analysis': {
                'name': '分析模式', 
                'description': '深度系统分析和问题诊断',
                'welcome': '分析模式启动，开始系统深度分析',
                'system_prompt': '你专注于系统分析和问题诊断，提供深入的洞察和解决方案。'
            }
        }
        
        self.current_mode = 'standard'
        
        # 启动系统监控
        self.monitoring = False
        self.start_system_monitor()
    
    def init_memory_db(self):
        """初始化记忆数据库"""
        try:
            conn = sqlite3.connect(self.memory_db)
            cursor = conn.cursor()
            
            # 创建用户偏好表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS user_preferences (
                    key TEXT PRIMARY KEY,
                    value TEXT,
                    last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 创建对话记忆表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS conversation_memory (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_input TEXT,
                    agent_response TEXT,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    tags TEXT
                )
            ''')
            
            # 创建任务记录表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS task_history (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    task_type TEXT,
                    description TEXT,
                    status TEXT,
                    result TEXT,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"记忆数据库初始化失败: {e}")
    
    def init_scheduler(self):
        """初始化任务调度器"""
        def scheduler_worker():
            while True:
                schedule.run_pending()
                time.sleep(1)
        
        scheduler_thread = threading.Thread(target=scheduler_worker, daemon=True)
        scheduler_thread.start()
    
    def load_plugins(self):
        """加载插件系统"""
        plugins_dir = "plugins"
        if not os.path.exists(plugins_dir):
            os.makedirs(plugins_dir)
        
        # 这里可以加载自定义插件
        self.plugins['system_monitor'] = self.system_monitor_plugin
        self.plugins['file_organizer'] = self.file_organizer_plugin
        self.plugins['network_tools'] = self.network_tools_plugin
    
    def system_monitor_plugin(self, action, **kwargs):
        """系统监控插件"""
        if action == "cpu_usage":
            return f"CPU使用率: {psutil.cpu_percent()}%"
        elif action == "memory_usage":
            memory = psutil.virtual_memory()
            return f"内存使用: {memory.percent}% ({memory.used//1024//1024}MB/{memory.total//1024//1024}MB)"
        elif action == "disk_usage":
            disk = psutil.disk_usage('/')
            return f"磁盘使用: {disk.percent}% ({disk.used//1024//1024}MB/{disk.total//1024//1024}MB)"
        return "未知操作"
    
    def file_organizer_plugin(self, action, **kwargs):
        """文件整理插件"""
        if action == "clean_temp":
            cleaned = self.clean_temp_files()
            return f"清理了 {cleaned} 个临时文件"
        elif action == "organize_downloads":
            organized = self.organize_downloads()
            return f"整理了 {organized} 个下载文件"
        return "未知操作"
    
    def network_tools_plugin(self, action, **kwargs):
        """网络工具插件"""
        if action == "speed_test":
            return self.network_speed_test()
        elif action == "check_ports":
            return self.check_open_ports()
        return "未知操作"
    
    def get_system_info(self):
        """获取系统信息"""
        try:
            system = platform.system()
            release = platform.release()
            version = platform.version()
            processor = platform.processor()
            architecture = platform.architecture()[0]
            
            # 内存信息
            memory = psutil.virtual_memory()
            total_memory = round(memory.total / (1024**3), 2)
            available_memory = round(memory.available / (1024**3), 2)
            
            # 磁盘信息
            disk = psutil.disk_usage('/')
            total_disk = round(disk.total / (1024**3), 2)
            free_disk = round(disk.free / (1024**3), 2)
            
            # CPU信息
            cpu_count = psutil.cpu_count()
            cpu_percent = psutil.cpu_percent(interval=1)
            
            info = f"""
- 操作系统: {system} {release}
- 系统版本: {version}
- 处理器: {processor}
- 架构: {architecture}
- 内存: {available_memory}GB / {total_memory}GB 可用
- 磁盘: {free_disk}GB / {total_disk}GB 可用
- CPU: {cpu_count} 核心, 使用率: {cpu_percent}%
"""
            return info
        except Exception as e:
            return f"系统信息获取失败: {str(e)}"
    
    def get_user_preferences(self):
        """获取用户偏好"""
        try:
            conn = sqlite3.connect(self.memory_db)
            cursor = conn.cursor()
            cursor.execute("SELECT key, value FROM user_preferences")
            preferences = cursor.fetchall()
            conn.close()
            
            if preferences:
                return "\n".join([f"- {key}: {value}" for key, value in preferences])
            else:
                return "暂无用户偏好记录"
        except:
            return "用户偏好数据库不可用"
    
    def save_user_preference(self, key, value):
        """保存用户偏好"""
        try:
            conn = sqlite3.connect(self.memory_db)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT OR REPLACE INTO user_preferences (key, value) VALUES (?, ?)",
                (key, value)
            )
            conn.commit()
            conn.close()
            return True
        except Exception as e:
            print(f"保存用户偏好失败: {e}")
            return False
    
    def record_conversation(self, user_input, agent_response, tags=""):
        """记录对话到记忆"""
        try:
            conn = sqlite3.connect(self.memory_db)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO conversation_memory (user_input, agent_response, tags) VALUES (?, ?, ?)",
                (user_input, agent_response, tags)
            )
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"记录对话失败: {e}")
    
    def record_task(self, task_type, description, status, result):
        """记录任务历史"""
        try:
            conn = sqlite3.connect(self.memory_db)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO task_history (task_type, description, status, result) VALUES (?, ?, ?, ?)",
                (task_type, description, status, result)
            )
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"记录任务失败: {e}")
    
    def start_system_monitor(self):
        """启动系统监控"""
        def monitor():
            self.monitoring = True
            while self.monitoring:
                try:
                    # 监控CPU使用率
                    cpu_usage = psutil.cpu_percent(interval=1)
                    if cpu_usage > 80:
                        self.record_task("monitor", f"CPU使用率过高: {cpu_usage}%", "warning", "建议检查运行进程")
                    
                    # 监控内存使用
                    memory = psutil.virtual_memory()
                    if memory.percent > 85:
                        self.record_task("monitor", f"内存使用率过高: {memory.percent}%", "warning", "建议释放内存")
                    
                    time.sleep(60)  # 每分钟检查一次
                except:
                    time.sleep(60)
        
        monitor_thread = threading.Thread(target=monitor, daemon=True)
        monitor_thread.start()
    
    def clean_temp_files(self):
        """清理临时文件"""
        try:
            temp_dirs = []
            if platform.system() == "Windows":
                temp_dirs = [
                    os.environ.get('TEMP', ''),
                    os.environ.get('TMP', ''),
                    r'C:\Windows\Temp'
                ]
            else:
                temp_dirs = ['/tmp', '/var/tmp']
            
            cleaned_count = 0
            for temp_dir in temp_dirs:
                if os.path.exists(temp_dir):
                    for root, dirs, files in os.walk(temp_dir):
                        for file in files:
                            try:
                                file_path = os.path.join(root, file)
                                # 只删除较旧的文件
                                if os.path.getctime(file_path) < time.time() - 7 * 24 * 3600:
                                    os.remove(file_path)
                                    cleaned_count += 1
                            except:
                                continue
            
            self.record_task("cleanup", "清理临时文件", "completed", f"清理了 {cleaned_count} 个文件")
            return cleaned_count
        except Exception as e:
            self.record_task("cleanup", "清理临时文件", "failed", str(e))
            return 0
    
    def organize_downloads(self):
        """整理下载文件夹"""
        try:
            downloads_dir = os.path.expanduser('~/Downloads')
            if not os.path.exists(downloads_dir):
                return 0
            
            file_types = {
                'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
                'Documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.xls', '.xlsx', '.ppt', '.pptx'],
                'Archives': ['.zip', '.rar', '.7z', '.tar', '.gz'],
                'Programs': ['.exe', '.msi', '.dmg', '.pkg', '.deb', '.rpm'],
                'Media': ['.mp4', '.avi', '.mkv', '.mp3', '.wav', '.flac']
            }
            
            organized_count = 0
            for filename in os.listdir(downloads_dir):
                file_path = os.path.join(downloads_dir, filename)
                if os.path.isfile(file_path):
                    _, ext = os.path.splitext(filename)
                    ext = ext.lower()
                    
                    for folder, extensions in file_types.items():
                        if ext in extensions:
                            folder_path = os.path.join(downloads_dir, folder)
                            if not os.path.exists(folder_path):
                                os.makedirs(folder_path)
                            
                            new_path = os.path.join(folder_path, filename)
                            if not os.path.exists(new_path):
                                shutil.move(file_path, new_path)
                                organized_count += 1
                            break
            
            self.record_task("organize", "整理下载文件夹", "completed", f"整理了 {organized_count} 个文件")
            return organized_count
        except Exception as e:
            self.record_task("organize", "整理下载文件夹", "failed", str(e))
            return 0
    
    def network_speed_test(self):
        """网络速度测试"""
        try:
            # 简单的速度测试实现
            import speedtest
            st = speedtest.Speedtest()
            download_speed = st.download() / 1_000_000  # 转换为 Mbps
            upload_speed = st.upload() / 1_000_000
            return f"下载速度: {download_speed:.2f} Mbps, 上传速度: {upload_speed:.2f} Mbps"
        except:
            return "速度测试需要安装speedtest-cli: pip install speedtest-cli"
    
    def check_open_ports(self):
        """检查开放端口"""
        try:
            open_ports = []
            for port in range(1, 100):
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(1)
                result = sock.connect_ex(('127.0.0.1', port))
                if result == 0:
                    open_ports.append(port)
                sock.close()
            
            return f"本地开放端口: {', '.join(map(str, open_ports))}"
        except Exception as e:
            return f"端口扫描失败: {e}"
    
    def convert_think_tags(self, text):
        """将<think>思考内容</think>转换为**[思考内容]**粗体格式"""
        if not text:
            return text
            
        pattern = r'<think>(.*?)</think>'
        
        def replace_think(match):
            think_content = match.group(1).strip()
            return f"**[{think_content}]**"
        
        converted_text = re.sub(pattern, replace_think, text, flags=re.DOTALL)
        return converted_text
        
    def parse_operations(self, text):
        """解析AI回复中的操作标签"""
        if not text:
            return text, []
            
        operations = []
        
        # 定义所有操作模式的正则表达式和替换函数
        patterns = [
            # 文件操作
            (r'<delfile>(.*?)</delfile>', lambda m: self.add_operation(operations, 'delete_file', {'path': m.group(1).strip()}, f"删除文件: {m.group(1).strip()}")),
            (r'<openfile>(.*?)</openfile>', lambda m: self.add_operation(operations, 'open_file', {'path': m.group(1).strip()}, f"打开文件: {m.group(1).strip()}")),
            (r'<openfolder>(.*?)</openfolder>', lambda m: self.add_operation(operations, 'open_folder', {'path': m.group(1).strip()}, f"打开文件夹: {m.group(1).strip()}")),
            (r'<createfile type="(.*?)" path="(.*?)">(.*?)</createfile>', lambda m: self.add_operation(operations, 'create_file', {'file_type': m.group(1).strip(), 'path': m.group(2).strip(), 'content': m.group(3).strip()}, f"创建文件: {m.group(2).strip()}")),
            (r'<rename old="(.*?)" new="(.*?)"></rename>', lambda m: self.add_operation(operations, 'rename', {'old_path': m.group(1).strip(), 'new_path': m.group(2).strip()}, f"重命名: {m.group(1).strip()} -> {m.group(2).strip()}")),
            (r'<copyfile source="(.*?)" destination="(.*?)"></copyfile>', lambda m: self.add_operation(operations, 'copy_file', {'source': m.group(1).strip(), 'destination': m.group(2).strip()}, f"复制文件: {m.group(1).strip()} -> {m.group(2).strip()}")),
            (r'<movefile source="(.*?)" destination="(.*?)"></movefile>', lambda m: self.add_operation(operations, 'move_file', {'source': m.group(1).strip(), 'destination': m.group(2).strip()}, f"移动文件: {m.group(1).strip()} -> {m.group(2).strip()}")),
            (r'<fileinfo>(.*?)</fileinfo>', lambda m: self.add_operation(operations, 'file_info', {'path': m.group(1).strip()}, f"获取文件信息: {m.group(1).strip()}")),
            
            # 系统操作
            (r'<runcommand>(.*?)</runcommand>', lambda m: self.add_operation(operations, 'run_command', {'command': m.group(1).strip()}, f"执行命令: {m.group(1).strip()}")),
            (r'<tasklist></tasklist>', lambda m: self.add_operation(operations, 'task_list', {}, "显示进程列表")),
            (r'<killtask>(.*?)</killtask>', lambda m: self.add_operation(operations, 'kill_task', {'task': m.group(1).strip()}, f"结束进程: {m.group(1).strip()}")),
            (r'<systeminfo></systeminfo>', lambda m: self.add_operation(operations, 'system_info', {}, "显示系统信息")),
            (r'<shutdown delay="(.*?)"></shutdown>', lambda m: self.add_operation(operations, 'shutdown', {'delay': m.group(1).strip()}, f"关机 (延迟: {m.group(1).strip()}秒)")),
            (r'<restart delay="(.*?)"></restart>', lambda m: self.add_operation(operations, 'restart', {'delay': m.group(1).strip()}, f"重启 (延迟: {m.group(1).strip()}秒)")),
            (r'<sleeppc delay="(.*?)"></sleeppc>', lambda m: self.add_operation(operations, 'sleep_pc', {'delay': m.group(1).strip()}, f"睡眠 (延迟: {m.group(1).strip()}秒)")),
            (r'<service control="(.*?)" name="(.*?)"></service>', lambda m: self.add_operation(operations, 'service_control', {'control': m.group(1).strip(), 'name': m.group(2).strip()}, f"服务管理: {m.group(1).strip()} {m.group(2).strip()}")),
            
            # 网络操作
            (r'<openurl>(.*?)</openurl>', lambda m: self.add_operation(operations, 'open_url', {'url': m.group(1).strip()}, f"打开网址: {m.group(1).strip()}")),
            (r'<ping>(.*?)</ping>', lambda m: self.add_operation(operations, 'ping', {'host': m.group(1).strip()}, f"Ping测试: {m.group(1).strip()}")),
            (r'<ipconfig></ipconfig>', lambda m: self.add_operation(operations, 'ipconfig', {}, "显示网络配置")),
            (r'<download url="(.*?)" path="(.*?)"></download>', lambda m: self.add_operation(operations, 'download', {'url': m.group(1).strip(), 'path': m.group(2).strip()}, f"下载文件: {m.group(1).strip()} -> {m.group(2).strip()}")),
            (r'<portscan host="(.*?)" ports="(.*?)"></portscan>', lambda m: self.add_operation(operations, 'port_scan', {'host': m.group(1).strip(), 'ports': m.group(2).strip()}, f"端口扫描: {m.group(1).strip()} 端口 {m.group(2).strip()}")),
            
            # 开发工具
            (r'<runcode language="(.*?)" code="(.*?)"></runcode>', lambda m: self.add_operation(operations, 'run_code', {'language': m.group(1).strip(), 'code': m.group(2).strip()}, f"运行代码: {m.group(1).strip()}")),
            (r'<createproject type="(.*?)" path="(.*?)" name="(.*?)"></createproject>', lambda m: self.add_operation(operations, 'create_project', {'project_type': m.group(1).strip(), 'path': m.group(2).strip(), 'name': m.group(3).strip()}, f"创建项目: {m.group(3).strip()} ({m.group(1).strip()})")),
            (r'<git operation="(.*?)" repo="(.*?)"></git>', lambda m: self.add_operation(operations, 'git_operation', {'operation': m.group(1).strip(), 'repo': m.group(2).strip()}, f"Git操作: {m.group(1).strip()} {m.group(2).strip()}")),
            
            # 自动化任务
            (r'<schedule task="(.*?)" interval="(.*?)" action="(.*?)"></schedule>', lambda m: self.add_operation(operations, 'schedule_task', {'task': m.group(1).strip(), 'interval': m.group(2).strip(), 'action': m.group(3).strip()}, f"计划任务: {m.group(1).strip()} 每 {m.group(2).strip()}")),
            (r'<automate task="(.*?)"></automate>', lambda m: self.add_operation(operations, 'automate_task', {'task': m.group(1).strip()}, f"自动化任务: {m.group(1).strip()}")),
            (r'<monitor resource="(.*?)" threshold="(.*?)"></monitor>', lambda m: self.add_operation(operations, 'monitor_resource', {'resource': m.group(1).strip(), 'threshold': m.group(2).strip()}, f"资源监控: {m.group(1).strip()} 阈值 {m.group(2).strip()}")),
            
            # 智能分析
            (r'<analyze system="(.*?)"></analyze>', lambda m: self.add_operation(operations, 'analyze_system', {'target': m.group(1).strip()}, f"系统分析: {m.group(1).strip()}")),
            (r'<optimize target="(.*?)"></optimize>', lambda m: self.add_operation(operations, 'optimize_system', {'target': m.group(1).strip()}, f"系统优化: {m.group(1).strip()}")),
            (r'<diagnose issue="(.*?)"></diagnose>', lambda m: self.add_operation(operations, 'diagnose_issue', {'issue': m.group(1).strip()}, f"问题诊断: {m.group(1).strip()}")),
            
            # 数据操作
            (r'<setclipboard>(.*?)</setclipboard>', lambda m: self.add_operation(operations, 'set_clipboard', {'content': m.group(1).strip()}, f"设置剪贴板内容")),
            (r'<getclipboard></getclipboard>', lambda m: self.add_operation(operations, 'get_clipboard', {}, "获取剪贴板内容")),
            (r'<database operation="(.*?)" query="(.*?)"></database>', lambda m: self.add_operation(operations, 'database_operation', {'operation': m.group(1).strip(), 'query': m.group(2).strip()}, f"数据库操作: {m.group(1).strip()}")),
            
            # 其他工具
            (r'<screenshot path="(.*?)"></screenshot>', lambda m: self.add_operation(operations, 'screenshot', {'path': m.group(1).strip()}, f"截取屏幕: {m.group(1).strip()}")),
            (r'<createdir>(.*?)</createdir>', lambda m: self.add_operation(operations, 'create_dir', {'path': m.group(1).strip()}, f"创建目录: {m.group(1).strip()}")),
            (r'<deldir>(.*?)</deldir>', lambda m: self.add_operation(operations, 'delete_dir', {'path': m.group(1).strip()}, f"删除目录: {m.group(1).strip()}")),
            (r'<listdir>(.*?)</listdir>', lambda m: self.add_operation(operations, 'list_dir', {'path': m.group(1).strip()}, f"列出目录: {m.group(1).strip()}")),
        ]
        
        converted_text = text
        for pattern, replacement_func in patterns:
            converted_text = re.sub(pattern, replacement_func, converted_text, flags=re.DOTALL)
        
        return converted_text, operations
    
    def add_operation(self, operations, op_type, params, description):
        """添加操作到列表"""
        operation = {'type': op_type, 'description': description}
        operation.update(params)
        operations.append(operation)
        return f"【{description}】"
    
    def execute_operation(self, operation):
        """执行单个操作"""
        try:
            op_type = operation['type']
            
            if op_type == 'delete_file':
                path = operation['path']
                if os.path.exists(path):
                    os.remove(path)
                    result = f"成功删除文件: {path}"
                else:
                    result = f"文件不存在: {path}"
                    
            elif op_type == 'open_file':
                path = operation['path']
                if os.path.exists(path):
                    if platform.system() == "Windows":
                        os.startfile(path)
                    elif platform.system() == "Darwin":
                        subprocess.run(["open", path])
                    else:
                        subprocess.run(["xdg-open", path])
                    result = f"成功打开文件: {path}"
                else:
                    result = f"文件不存在: {path}"
                    
            elif op_type == 'open_folder':
                path = operation['path']
                if os.path.exists(path):
                    if platform.system() == "Windows":
                        os.startfile(path)
                    elif platform.system() == "Darwin":
                        subprocess.run(["open", path])
                    else:
                        subprocess.run(["xdg-open", path])
                    result = f"成功打开文件夹: {path}"
                else:
                    result = f"文件夹不存在: {path}"
                    
            elif op_type == 'create_file':
                file_type = operation['file_type']
                path = operation['path']
                content = operation['content']
                
                if not path.endswith(f".{file_type}"):
                    path = f"{path}.{file_type}"
                    
                directory = os.path.dirname(path)
                if directory and not os.path.exists(directory):
                    os.makedirs(directory, exist_ok=True)
                
                with open(path, 'w', encoding='utf-8') as f:
                    f.write(content)
                
                result = f"成功创建文件: {path} (内容长度: {len(content)} 字符)"
            
            elif op_type == 'rename':
                old_path = operation['old_path']
                new_path = operation['new_path']
                
                if os.path.exists(old_path):
                    new_dir = os.path.dirname(new_path)
                    if new_dir and not os.path.exists(new_dir):
                        os.makedirs(new_dir, exist_ok=True)
                    
                    os.rename(old_path, new_path)
                    result = f"成功重命名: {old_path} -> {new_path}"
                else:
                    result = f"原路径不存在: {old_path}"
            
            elif op_type == 'copy_file':
                source = operation['source']
                destination = operation['destination']
                
                if os.path.exists(source):
                    shutil.copy2(source, destination)
                    result = f"成功复制文件: {source} -> {destination}"
                else:
                    result = f"源文件不存在: {source}"
            
            elif op_type == 'move_file':
                source = operation['source']
                destination = operation['destination']
                
                if os.path.exists(source):
                    shutil.move(source, destination)
                    result = f"成功移动文件: {source} -> {destination}"
                else:
                    result = f"源文件不存在: {source}"
            
            elif op_type == 'file_info':
                path = operation['path']
                if os.path.exists(path):
                    stat = os.stat(path)
                    size = stat.st_size
                    created = datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
                    modified = datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
                    
                    info = f"文件信息: {path}\n"
                    info += f"大小: {size} 字节\n"
                    info += f"创建时间: {created}\n"
                    info += f"修改时间: {modified}"
                    result = info
                else:
                    result = f"文件不存在: {path}"
            
            elif op_type == 'run_command':
                command = operation['command']
                try:
                    result_output = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
                    output = result_output.stdout if result_output.stdout else result_output.stderr
                    result = f"命令执行结果:\n{output}"
                except subprocess.TimeoutExpired:
                    result = "命令执行超时"
                except Exception as e:
                    result = f"命令执行失败: {str(e)}"
            
            elif op_type == 'task_list':
                processes = []
                for proc in psutil.process_iter(['pid', 'name', 'memory_percent', 'cpu_percent']):
                    try:
                        processes.append(proc.info)
                    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                        pass
                
                # 按内存使用排序
                processes.sort(key=lambda x: x['memory_percent'] or 0, reverse=True)
                
                result_text = "运行中的进程:\n"
                for proc in processes[:20]:  # 显示前20个
                    result_text += f"PID: {proc['pid']}, 名称: {proc['name']}, CPU: {proc['cpu_percent']:.1f}%, 内存: {proc['memory_percent']:.1f}%\n"
                
                result = result_text
            
            elif op_type == 'kill_task':
                task = operation['task']
                try:
                    # 尝试按PID结束进程
                    pid = int(task)
                    proc = psutil.Process(pid)
                    proc.terminate()
                    result = f"已结束进程 PID: {pid}"
                except (ValueError, psutil.NoSuchProcess):
                    # 按进程名结束
                    killed = 0
                    for proc in psutil.process_iter():
                        try:
                            if proc.name().lower() == task.lower():
                                proc.terminate()
                                killed += 1
                        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                            pass
                    
                    if killed > 0:
                        result = f"已结束 {killed} 个名为 '{task}' 的进程"
                    else:
                        result = f"未找到进程: {task}"
            
            elif op_type == 'system_info':
                result = self.system_info
            
            elif op_type == 'shutdown':
                delay = int(operation['delay'])
                if platform.system() == "Windows":
                    os.system(f"shutdown /s /t {delay}")
                else:  # Linux/macOS
                    os.system(f"shutdown -h +{delay//60}")
                result = f"系统将在 {delay} 秒后关机"
            
            elif op_type == 'restart':
                delay = int(operation['delay'])
                if platform.system() == "Windows":
                    os.system(f"shutdown /r /t {delay}")
                else:  # Linux/macOS
                    os.system(f"shutdown -r +{delay//60}")
                result = f"系统将在 {delay} 秒后重启"
            
            elif op_type == 'sleep_pc':
                delay = int(operation['delay'])
                time.sleep(delay)
                if platform.system() == "Windows":
                    os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
                elif platform.system() == "Darwin":
                    os.system("pmset sleepnow")
                else:  # Linux
                    os.system("systemctl suspend")
                result = f"系统将在 {delay} 秒后进入睡眠"
            
            elif op_type == 'service_control':
                control = operation['control']
                name = operation['name']
                if platform.system() == "Windows":
                    os.system(f"sc {control} {name}")
                else:  # Linux/macOS
                    os.system(f"systemctl {control} {name}")
                result = f"已执行服务操作: {control} {name}"
            
            elif op_type == 'open_url':
                url = operation['url']
                webbrowser.open(url)
                result = f"已打开网址: {url}"
            
            elif op_type == 'ping':
                host = operation['host']
                param = "-n 4" if platform.system().lower() == "windows" else "-c 4"
                command = f"ping {param} {host}"
                try:
                    result_output = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=10)
                    result = f"Ping结果:\n{result_output.stdout}"
                except subprocess.TimeoutExpired:
                    result = "Ping超时"
            
            elif op_type == 'ipconfig':
                if platform.system() == "Windows":
                    command = "ipconfig"
                else:  # Linux/macOS
                    command = "ifconfig"
                
                try:
                    result_output = subprocess.run(command, shell=True, capture_output=True, text=True)
                    result = f"网络配置:\n{result_output.stdout}"
                except Exception as e:
                    result = f"获取网络配置失败: {str(e)}"
            
            elif op_type == 'download':
                url = operation['url']
                path = operation['path']
                try:
                    response = requests.get(url, stream=True, timeout=30)
                    response.raise_for_status()
                    
                    with open(path, 'wb') as f:
                        for chunk in response.iter_content(chunk_size=8192):
                            f.write(chunk)
                    
                    result = f"文件下载成功: {path}"
                except Exception as e:
                    result = f"下载失败: {str(e)}"
            
            elif op_type == 'port_scan':
                host = operation['host']
                ports = operation['ports']
                try:
                    # 解析端口范围
                    if '-' in ports:
                        start_port, end_port = map(int, ports.split('-'))
                        port_range = range(start_port, end_port + 1)
                    else:
                        port_range = [int(ports)]
                    
                    open_ports = []
                    for port in port_range:
                        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        sock.settimeout(1)
                        result_scan = sock.connect_ex((host, port))
                        if result_scan == 0:
                            open_ports.append(port)
                        sock.close()
                    
                    result = f"端口扫描结果 {host}: 开放端口 {', '.join(map(str, open_ports))}"
                except Exception as e:
                    result = f"端口扫描失败: {e}"
            
            elif op_type == 'run_code':
                language = operation['language']
                code = operation['code']
                try:
                    # 简单的代码执行实现
                    if language == "python":
                        exec(code)
                        result = "Python代码执行完成"
                    else:
                        result = f"暂不支持 {language} 代码执行"
                except Exception as e:
                    result = f"代码执行失败: {e}"
            
            elif op_type == 'create_project':
                project_type = operation['project_type']
                path = operation['path']
                name = operation['name']
                project_path = os.path.join(path, name)
                
                try:
                    os.makedirs(project_path, exist_ok=True)
                    
                    # 根据项目类型创建基础文件
                    if project_type == "python":
                        with open(os.path.join(project_path, "main.py"), 'w') as f:
                            f.write('print("Hello World!")')
                    elif project_type == "web":
                        with open(os.path.join(project_path, "index.html"), 'w') as f:
                            f.write('<html><body><h1>Hello World!</h1></body></html>')
                    
                    result = f"成功创建 {project_type} 项目: {project_path}"
                except Exception as e:
                    result = f"创建项目失败: {e}"
            
            elif op_type == 'git_operation':
                operation_cmd = operation['operation']
                repo = operation['repo']
                try:
                    if operation_cmd == "clone":
                        subprocess.run(["git", "clone", repo], check=True)
                        result = f"成功克隆仓库: {repo}"
                    else:
                        result = f"暂不支持 Git 操作: {operation_cmd}"
                except Exception as e:
                    result = f"Git操作失败: {e}"
            
            elif op_type == 'schedule_task':
                task = operation['task']
                interval = operation['interval']
                action = operation['action']
                
                # 简单的任务调度实现
                def scheduled_job():
                    print(f"执行计划任务: {task}")
                
                if interval.endswith('m'):
                    minutes = int(interval[:-1])
                    schedule.every(minutes).minutes.do(scheduled_job)
                elif interval.endswith('h'):
                    hours = int(interval[:-1])
                    schedule.every(hours).hours.do(scheduled_job)
                
                self.scheduled_tasks.append(task)
                result = f"已计划任务: {task} 每 {interval} 执行"
            
            elif op_type == 'automate_task':
                task = operation['task']
                # 这里可以实现具体的自动化任务
                result = f"自动化任务已创建: {task}"
            
            elif op_type == 'monitor_resource':
                resource = operation['resource']
                threshold = operation['threshold']
                result = f"开始监控 {resource}，阈值: {threshold}"
            
            elif op_type == 'analyze_system':
                target = operation['target']
                # 系统分析实现
                result = f"系统分析完成: {target}"
            
            elif op_type == 'optimize_system':
                target = operation['target']
                # 系统优化实现
                result = f"系统优化完成: {target}"
            
            elif op_type == 'diagnose_issue':
                issue = operation['issue']
                # 问题诊断实现
                result = f"问题诊断完成: {issue}"
            
            elif op_type == 'set_clipboard':
                content = operation['content']
                try:
                    pyperclip.copy(content)
                    result = f"剪贴板内容已设置 (长度: {len(content)} 字符)"
                except Exception as e:
                    result = f"设置剪贴板失败: {str(e)}"
            
            elif op_type == 'get_clipboard':
                try:
                    content = pyperclip.paste()
                    result = f"剪贴板内容: {content}"
                except Exception as e:
                    result = f"获取剪贴板失败: {str(e)}"
            
            elif op_type == 'database_operation':
                operation_db = operation['operation']
                query = operation['query']
                # 简单的数据库操作实现
                result = f"数据库操作 {operation_db} 完成"
            
            elif op_type == 'screenshot':
                path = operation['path']
                try:
                    if platform.system() == "Windows":
                        # Windows截图
                        import pyautogui
                        screenshot = pyautogui.screenshot()
                        screenshot.save(path)
                    elif platform.system() == "Darwin":
                        # macOS截图
                        subprocess.run(["screencapture", path])
                    else:
                        # Linux截图 (需要安装scrot)
                        subprocess.run(["scrot", path])
                    result = f"截图已保存: {path}"
                except Exception as e:
                    result = f"截图失败: {str(e)}"
            
            elif op_type == 'create_dir':
                path = operation['path']
                os.makedirs(path, exist_ok=True)
                result = f"成功创建目录: {path}"
            
            elif op_type == 'delete_dir':
                path = operation['path']
                if os.path.exists(path):
                    shutil.rmtree(path)
                    result = f"成功删除目录: {path}"
                else:
                    result = f"目录不存在: {path}"
            
            elif op_type == 'list_dir':
                path = operation['path'] if operation['path'] else "."
                if os.path.exists(path):
                    items = os.listdir(path)
                    result_text = f"目录内容: {path}\n"
                    for item in items:
                        item_path = os.path.join(path, item)
                        if os.path.isdir(item_path):
                            result_text += f"[目录] {item}\n"
                        else:
                            size = os.path.getsize(item_path)
                            result_text += f"[文件] {item} ({size} 字节)\n"
                    result = result_text
                else:
                    result = f"目录不存在: {path}"
            
            else:
                result = f"未知操作类型: {op_type}"
            
            # 记录任务执行结果
            self.record_task(op_type, operation['description'], 'completed', result)
            return result
            
        except Exception as e:
            error_msg = f"操作失败: {str(e)}"
            self.record_task(op_type, operation['description'], 'failed', error_msg)
            return error_msg
    
    def confirm_and_execute_operations(self, operations):
        """确认并执行操作列表"""
        if not operations:
            return
            
        print("\n=== 待确认的操作 ===")
        for i, op in enumerate(operations, 1):
            print(f"{i}. {op['description']}")
            
            # 显示操作详情
            if op['type'] == 'create_file':
                content_preview = op['content'][:100] + "..." if len(op['content']) > 100 else op['content']
                print(f"   内容预览: {content_preview}")
            elif op['type'] == 'set_clipboard':
                content_preview = op['content'][:100] + "..." if len(op['content']) > 100 else op['content']
                print(f"   内容预览: {content_preview}")
        
        print("\n输入 /yes 确认执行所有操作")
        print("输入 /no 取消所有操作")
        print("输入 /cancel 取消单个操作（例如: /cancel 1）")
        
        while True:
            try:
                user_input = input("\n请输入命令: ").strip().lower()
                
                if user_input == '/yes':
                    print("\n正在执行操作...")
                    results = []
                    for op in operations:
                        result = self.execute_operation(op)
                        results.append(result)
                        print(f"- {result}")
                    print("所有操作已完成")
                    break
                    
                elif user_input == '/no':
                    print("已取消所有操作")
                    break
                    
                elif user_input.startswith('/cancel'):
                    parts = user_input.split()
                    if len(parts) == 2:
                        try:
                            index = int(parts[1]) - 1
                            if 0 <= index < len(operations):
                                removed_op = operations.pop(index)
                                print(f"已取消操作: {removed_op['description']}")
                                
                                if not operations:
                                    print("所有操作已取消")
                                    break
                                else:
                                    print("\n剩余操作:")
                                    for i, op in enumerate(operations, 1):
                                        print(f"{i}. {op['description']}")
                            else:
                                print("无效的操作编号")
                        except ValueError:
                            print("请使用数字指定要取消的操作，例如: /cancel 1")
                    else:
                        print("使用方法: /cancel [操作编号]")
                        
                else:
                    print("未知命令，请输入 /yes, /no 或 /cancel [编号]")
                    
            except KeyboardInterrupt:
                print("\n操作确认已取消")
                break
        
        # 清空待处理操作
        self.pending_operations = []
    
    def switch_mode(self, mode_id):
        """切换工作模式"""
        if mode_id in self.agent_modes:
            self.current_mode = mode_id
            # 更新系统提示词
            self.conversation_history[0] = {
                "role": "system",
                "content": self.agent_modes[mode_id]['system_prompt'] + f"\n\n当前系统信息：{self.system_info}"
            }
            return True
        return False
    
    def switch_model(self, model_index):
        """切换模型"""
        try:
            index = int(model_index) - 1
            if 0 <= index < len(self.supported_models):
                self.current_model = self.supported_models[index]
                return True
            else:
                return False
        except ValueError:
            return False
    
    def show_modes(self):
        """显示可用模式"""
        print("\n可用工作模式:")
        for i, (mode_id, mode_info) in enumerate(self.agent_modes.items(), 1):
            current_indicator = " (当前)" if mode_id == self.current_mode else ""
            print(f"{i}. {mode_info['name']}{current_indicator} - {mode_info['description']}")
        print()
    
    def show_models(self):
        """显示可用模型"""
        print("\n可用模型:")
        for i, model in enumerate(self.supported_models, 1):
            current_indicator = " (当前)" if model == self.current_model else ""
            print(f"{i}. {model}{current_indicator}")
        print()
    
    def send_message(self, message):
        """发送消息到API并获取回复"""
        # 添加用户消息到历史
        self.conversation_history.append({
            "role": "user",
            "content": message
        })
        
        # 准备请求数据
        data = {
            "model": self.current_model,
            "messages": self.conversation_history,
            "stream": False
        }
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        
        try:
            print(f"\nStar CE Agent ({self.agent_modes[self.current_mode]['name']}): ", end="", flush=True)
            
            response = requests.post(
                self.api_url,
                headers=headers,
                json=data,
                timeout=60
            )
            
            if response.status_code == 200:
                result = response.json()
                ai_response = result['choices'][0]['message']['content']
                
                # 转换think标签为粗体格式
                think_converted = self.convert_think_tags(ai_response)
                
                # 解析操作标签
                final_response, operations = self.parse_operations(think_converted)
                
                # 添加AI回复到历史
                self.conversation_history.append({
                    "role": "assistant",
                    "content": ai_response  # 保存原始内容
                })
                
                # 记录对话
                self.record_conversation(message, ai_response, self.current_mode)
                
                print(final_response)
                
                # 如果有操作需要确认，则提示用户
                if operations:
                    self.pending_operations = operations
                    self.confirm_and_execute_operations(operations)
                    
            else:
                print(f"API请求失败: {response.status_code} - {response.text}")
                
        except requests.exceptions.Timeout:
            print("请求超时，请稍后重试")
        except requests.exceptions.RequestException as e:
            print(f"网络错误: {e}")
        except Exception as e:
            print(f"发生错误: {e}")
    
    def clear_chat(self):
        """清除聊天历史"""
        self.conversation_history = [
            {
                "role": "system",
                "content": self.agent_modes[self.current_mode]['system_prompt'] + f"\n\n当前系统信息：{self.system_info}"
            }
        ]
        print("聊天记录已清除")
    
    def show_help(self):
        """显示帮助信息"""
        print("\n" + "="*60)
        print("              Star CE Agent - 全能AI智能体")
        print("="*60)
        print("命令:")
        print("  /help        - 显示此帮助信息")
        print("  /clear       - 清除聊天记录")
        print("  /modes       - 显示可用工作模式")
        print("  /models      - 显示可用模型")
        print("  /mode N      - 切换到第N个工作模式")
        print("  /model N     - 切换到第N个模型")
        print("  /exit        - 退出程序")
        print("  /save        - 保存聊天记录")
        print("  /load        - 加载聊天记录")
        print("  /about       - 关于此程序")
        print("  /status      - 显示系统状态")
        print("  /plugins     - 显示可用插件")
        print("  /memory      - 显示记忆统计")
        print("\n操作确认命令:")
        print("  /yes         - 确认执行所有待处理操作")
        print("  /no          - 取消所有待处理操作")
        print("  /cancel N    - 取消第N个待处理操作")
        print("\n支持的操作类型:")
        print("  • 文件管理系统: 创建/删除/复制/移动/重命名文件")
        print("  • 系统控制中心: 进程管理/关机/重启/系统信息")
        print("  • 网络工具箱: 打开网页/Ping测试/下载文件/端口扫描")
        print("  • 开发工具集: 运行代码/创建项目/Git操作")
        print("  • 自动化任务: 计划任务/资源监控")
        print("  • 智能分析: 系统分析/优化/问题诊断")
        print("  • 数据操作: 剪贴板/数据库操作")
        print("  • 其他工具: 截图/目录操作等")
        print("\n直接输入内容即可与AI对话")
        print("="*60)

    def show_about(self):
        """显示关于信息"""
        print("\n" + "="*50)
        print("           Star CE Agent V1.0")
        print("="*50)
        print("增强版AI智能体 - 全能电脑操作助手")
        print("原作者: FKingMIX3 Agent版作者:kunkun999")
        print("功能特性:")
        print("  • 7种智能工作模式")
        print("  • 记忆系统和用户偏好")
        print("  • 插件扩展架构")
        print("  • 自动化任务调度")
        print("  • 实时系统监控")
        print("  • 高级电脑操作能力")
        print("="*50)
    
    def show_status(self):
        """显示系统状态"""
        print("\n" + "="*40)
        print("         系统状态")
        print("="*40)
        print(f"当前模式: {self.agent_modes[self.current_mode]['name']}")
        print(f"当前模型: {self.current_model}")
        print(f"对话历史: {len(self.conversation_history)} 条消息")
        print(f"待处理操作: {len(self.pending_operations)} 个")
        print(f"系统监控: {'运行中' if self.monitoring else '已停止'}")
        print(f"计划任务: {len(self.scheduled_tasks)} 个")
        print("="*40)
    
    def show_plugins(self):
        """显示可用插件"""
        print("\n可用插件:")
        for i, (plugin_name, plugin_func) in enumerate(self.plugins.items(), 1):
            print(f"{i}. {plugin_name}")
        print()
    
    def show_memory_stats(self):
        """显示记忆统计"""
        try:
            conn = sqlite3.connect(self.memory_db)
            cursor = conn.cursor()
            
            # 获取对话记忆数量
            cursor.execute("SELECT COUNT(*) FROM conversation_memory")
            conv_count = cursor.fetchone()[0]
            
            # 获取任务记录数量
            cursor.execute("SELECT COUNT(*) FROM task_history")
            task_count = cursor.fetchone()[0]
            
            # 获取用户偏好数量
            cursor.execute("SELECT COUNT(*) FROM user_preferences")
            pref_count = cursor.fetchone()[0]
            
            conn.close()
            
            print(f"\n记忆统计:")
            print(f"对话记忆: {conv_count} 条")
            print(f"任务记录: {task_count} 条")
            print(f"用户偏好: {pref_count} 条")
            
        except Exception as e:
            print(f"获取记忆统计失败: {e}")
    
    def save_chat(self, filename=None):
        """保存聊天记录"""
        if not filename:
            filename = f"star_ce_chat_{self.current_mode}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump({
                    'mode': self.current_mode,
                    'model': self.current_model,
                    'history': self.conversation_history,
                    'timestamp': datetime.now().isoformat()
                }, f, ensure_ascii=False, indent=2)
            print(f"聊天记录已保存到: {filename}")
        except Exception as e:
            print(f"保存失败: {e}")
    
    def load_chat(self, filename=None):
        """加载聊天记录"""
        if not filename:
            # 查找最新的聊天记录
            chat_files = [f for f in os.listdir('.') if f.startswith('star_ce_chat_') and f.endswith('.json')]
            if not chat_files:
                print("未找到聊天记录文件")
                return
            filename = max(chat_files, key=os.path.getctime)
        
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
                self.current_mode = data.get('mode', self.current_mode)
                self.current_model = data.get('model', self.current_model)
                self.conversation_history = data['history']
            print(f"聊天记录已从 {filename} 加载")
        except FileNotFoundError:
            print(f"文件 {filename} 不存在")
        except Exception as e:
            print(f"加载失败: {e}")
    
    def run(self):
        """运行主程序"""
        print(r"""
    _________ __           __________ _____ 
   / __/ __// /          / __/ __/ // / _ \
  / _/_\ \ / /__  ___   / _/_\ \/ _  / // /
 /___/___//____/ /_/   /___/___/_//_/____/ 
        """)
        print("Star CE Agent - 全能AI智能体已启动")
        print("输入 /help 查看可用命令")
        print(f"当前模式: {self.agent_modes[self.current_mode]['name']}")
        print(f"当前模型: {self.current_model}")
        print(f"欢迎语: {self.agent_modes[self.current_mode]['welcome']}")
        print("=" * 60)
        
        while True:
            try:
                user_input = input("\n你: ").strip()
                
                if not user_input:
                    continue
                
                # 处理命令
                if user_input.startswith('/'):
                    command = user_input[1:].lower()
                    
                    if command == 'help':
                        self.show_help()
                    elif command == 'about':
                        self.show_about()
                    elif command == 'clear':
                        self.clear_chat()
                    elif command == 'modes':
                        self.show_modes()
                    elif command == 'models':
                        self.show_models()
                    elif command == 'status':
                        self.show_status()
                    elif command == 'plugins':
                        self.show_plugins()
                    elif command == 'memory':
                        self.show_memory_stats()
                    elif command.startswith('mode'):
                        parts = command.split()
                        if len(parts) == 2:
                            try:
                                mode_index = int(parts[1]) - 1
                                mode_ids = list(self.agent_modes.keys())
                                if 0 <= mode_index < len(mode_ids):
                                    mode_id = mode_ids[mode_index]
                                    if self.switch_mode(mode_id):
                                        print(f"已切换到: {self.agent_modes[mode_id]['name']}")
                                        print(f"欢迎语: {self.agent_modes[mode_id]['welcome']}")
                                    else:
                                        print("模式切换失败")
                                else:
                                    print("无效的模式编号")
                            except ValueError:
                                print("请使用数字选择模式，例如: /mode 1")
                        else:
                            print("使用方法: /mode [模式编号]")
                            self.show_modes()
                    elif command.startswith('model'):
                        parts = command.split()
                        if len(parts) == 2:
                            if self.switch_model(parts[1]):
                                print(f"已切换到模型: {self.current_model}")
                            else:
                                print("无效的模型编号")
                        else:
                            print("使用方法: /model [模型编号]")
                            self.show_models()
                    elif command == 'exit':
                        print("Star CE Agent 已关闭，再见！")
                        break
                    elif command == 'save':
                        self.save_chat()
                    elif command == 'load':
                        self.load_chat()
                    elif command == 'yes' and self.pending_operations:
                        # 执行待处理操作
                        self.confirm_and_execute_operations(self.pending_operations)
                    elif command == 'no' and self.pending_operations:
                        print("已取消所有待处理操作")
                        self.pending_operations = []
                    elif command.startswith('cancel') and self.pending_operations:
                        parts = command.split()
                        if len(parts) == 2:
                            try:
                                index = int(parts[1]) - 1
                                if 0 <= index < len(self.pending_operations):
                                    removed_op = self.pending_operations.pop(index)
                                    print(f"已取消操作: {removed_op['description']}")
                                    
                                    if not self.pending_operations:
                                        print("所有操作已取消")
                                else:
                                    print("无效的操作编号")
                            except ValueError:
                                print("请使用数字指定要取消的操作，例如: /cancel 1")
                        else:
                            print("使用方法: /cancel [操作编号]")
                    else:
                        print("未知命令，输入 /help 查看可用命令")
                
                # 处理普通消息
                else:
                    self.send_message(user_input)
                    
            except KeyboardInterrupt:
                print("\n\nStar CE Agent 已关闭，再见！")
                break
            except EOFError:
                print("\n\nStar CE Agent 已关闭，再见！")
                break

def main():
    # 创建并运行智能体
    agent = StarCEAgent()
    agent.run()

if __name__ == "__main__":
    main()